package com.adams.app.ui;

import java.util.ArrayList;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.ListView;
import android.widget.Toast;

import com.adams.app.R;
import com.adams.app.data.GsonRequest;
import com.adams.app.data.RequestManager;
import com.adams.app.model.Picture;
import com.adams.app.ui.adapter.ImgItemsAdapter;
import com.adams.app.utils.CommonUtils;
import com.adams.app.vendor.HappyGyApi;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;

public class ImgShowActivity extends ActionBarActivity {

	private long id;
	private ListView listViewLeft;
	private ListView listViewRight;
	private ImgItemsAdapter leftAdapter;
	private ImgItemsAdapter rightAdapter;

	private ArrayList<Picture> listUrl;

	int[] leftViewsHeights;
	int[] rightViewsHeights;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_image_show);

		id = getIntent().getExtras().getLong("id");

		listViewLeft = (ListView) findViewById(R.id.list_view_left);
		listViewRight = (ListView) findViewById(R.id.list_view_right);

		loadData();

		listViewLeft.setOnTouchListener(touchListener);
		listViewRight.setOnTouchListener(touchListener);
		listViewLeft.setOnScrollListener(scrollListener);
		listViewRight.setOnScrollListener(scrollListener);
	}

	// Passing the touch event to the opposite list
	OnTouchListener touchListener = new OnTouchListener() {
		boolean dispatched = false;

		@Override
		public boolean onTouch(View v, MotionEvent event) {
			if (v.equals(listViewLeft) && !dispatched) {
				dispatched = true;
				listViewRight.dispatchTouchEvent(event);
			} else if (v.equals(listViewRight) && !dispatched) {
				dispatched = true;
				listViewLeft.dispatchTouchEvent(event);
			}

			dispatched = false;
			return false;
		}
	};

	/**
	 * Synchronizing scrolling Distance from the top of the first visible
	 * element opposite list: sum_heights(opposite invisible screens) -
	 * sum_heights(invisible screens) + distance from top of the first visible
	 * child
	 */
	OnScrollListener scrollListener = new OnScrollListener() {

		@Override
		public void onScrollStateChanged(AbsListView v, int scrollState) {
		}

		@Override
		public void onScroll(AbsListView view, int firstVisibleItem,
				int visibleItemCount, int totalItemCount) {

			if (view.getChildAt(0) != null) {
				if (view.equals(listViewLeft)) {
					leftViewsHeights[view.getFirstVisiblePosition()] = view
							.getChildAt(0).getHeight();

					int h = 0;
					for (int i = 0; i < listViewRight.getFirstVisiblePosition(); i++) {
						h += rightViewsHeights[i];
					}

					int hi = 0;
					for (int i = 0; i < listViewLeft.getFirstVisiblePosition(); i++) {
						hi += leftViewsHeights[i];
					}

					int top = h - hi + view.getChildAt(0).getTop();
					listViewRight.setSelectionFromTop(
							listViewRight.getFirstVisiblePosition(), top);
				} else if (view.equals(listViewRight)) {
					rightViewsHeights[view.getFirstVisiblePosition()] = view
							.getChildAt(0).getHeight();

					int h = 0;
					for (int i = 0; i < listViewLeft.getFirstVisiblePosition(); i++) {
						h += leftViewsHeights[i];
					}

					int hi = 0;
					for (int i = 0; i < listViewRight.getFirstVisiblePosition(); i++) {
						hi += rightViewsHeights[i];
					}

					int top = h - hi + view.getChildAt(0).getTop();
					listViewLeft.setSelectionFromTop(
							listViewLeft.getFirstVisiblePosition(), top);
				}

			}

		}
	};

	private void loadItems() {
		int len = listUrl.size();
		if (len > 0) {
			String[] leftItems = new String[len / 2];
			String[] rightItems = new String[len - leftItems.length];

			int i;
			for (i = 0; i < len / 2; i++) {
				leftItems[i] = listUrl.get(i).getUrlPic();
				rightItems[i] = listUrl.get(len - i - 1).getUrlPic();
			}
			
			leftAdapter = new ImgItemsAdapter(this, R.layout.listitem_image,
					leftItems);
			rightAdapter = new ImgItemsAdapter(this, R.layout.listitem_image,
					rightItems);
			listViewLeft.setAdapter(leftAdapter);
			listViewRight.setAdapter(rightAdapter);

			leftViewsHeights = new int[leftItems.length];
			rightViewsHeights = new int[rightItems.length];
		}
	}

	public void loadData() {
		executeRequest(new GsonRequest<Picture.PictureRequestData>(
				String.format(HappyGyApi.IMAGE_LIST, id),
				Picture.PictureRequestData.class, null,
				new Response.Listener<Picture.PictureRequestData>() {
					@Override
					public void onResponse(
							final Picture.PictureRequestData requestData) {
						CommonUtils
								.executeAsyncTask(new AsyncTask<Object, Object, Object>() {
									@Override
									protected Object doInBackground(
											Object... params) {
										return requestData;
									}

									@Override
									protected void onPostExecute(Object o) {
										super.onPostExecute(o);
										listUrl = ((Picture.PictureRequestData) o)
												.getPictures();
										loadItems();
									}
								});
					}
				}, new Response.ErrorListener() {
					@Override
					public void onErrorResponse(VolleyError volleyError) {
						Toast.makeText(ImgShowActivity.this,
								R.string.refresh_list_failed,
								Toast.LENGTH_SHORT).show();
					}
				}));
	}

	@Override
	public void onStop() {
		super.onStop();
		RequestManager.cancelAll(this);
	}

	protected void executeRequest(Request<?> request) {
		RequestManager.addRequest(request, this);
	}
}